<script setup>
import { ref, reactive, computed } from "vue";

// 时间轴状态：轨道列表、缩放比例、滚动偏移、选中片段
// 轨道数据（模拟更多轨道用于测试虚拟滚动）
const tracks = ref(Array.from({ length: 20 }, (_, i) => ({
  id: `track-${i}`,
  type: ['video', 'audio', 'subtitle'][i % 3],
  clips: []
})));
const zoom = ref(100); // 百分比缩放
const scrollX = ref(0);
const selectedClip = ref(null);

// 虚拟滚动相关状态
const trackHeight = 80; // 单个轨道高度（px）
const visibleTrackCount = 5; // 可视区域轨道数量
const scrollY = ref(0); // 垂直滚动偏移
const visibleStart = computed(() => Math.floor(scrollY.value / trackHeight));
const visibleEnd = computed(() => visibleStart.value + visibleTrackCount);
const visibleTracks = computed(() => tracks.value.slice(visibleStart.value, visibleEnd.value));

// 时间轴尺寸计算（容器宽度响应式）
const containerWidth = ref(1200);
const timelineWidth = () => containerWidth.value * (zoom.value / 100);

// 像素与时间转换（假设100px=1秒）
const pxPerSecond = () => 100 * (zoom.value / 100);
const timeToPx = (time) => time * pxPerSecond();
const pxToTime = (px) => px / pxPerSecond();

// 视频帧处理（假设默认30fps）
const fps = ref(30);
const frameToTime = (frame) => frame / fps.value;
const timeToFrame = (time) => Math.round(time * fps.value);

// 添加删除片段方法
const handleDeleteClip = (clipId) => {
  tracks.value = tracks.value.map(track => ({
    ...track,
    clips: track.clips.filter(clip => clip.id !== clipId)
  }));
  if (currentClip.value?.id === clipId) currentClip.value = null;
};

// 更新调整片段时长方法
const handleResize = (clipId, direction, deltaTime) => {
  tracks.value = tracks.value.map(track => ({
    ...track,
    clips: track.clips.map(clip => {
      if (clip.id === clipId) {
        const newStart = direction === 'left' ? Math.max(0, clip.start + deltaTime) : clip.start;
        const newDuration = Math.max(0.5, clip.duration + (direction === 'left' ? -deltaTime : deltaTime));
        return { ...clip, start: newStart, duration: newDuration };
      }
      return clip;
    })
  }));
};
</script>

<template>
    <div class="timeline-container">
    <!-- 时间轴头部刻度 -->
    <div class="timeline-header" :style="{ width: `${timelineWidth()}px` }">
      <div
        class="time-marker"
        v-for="i in 10"
        :key="i"
        :style="{ left: `${i * 100 * (zoom.value / 100)}px` }"
      >
        {{ i }}s
      </div>
    </div>

    <!-- 轨道区域 -->
    <div class="tracks-container" :style="{ width: `${timelineWidth()}px`, height: `${(tracks.value || []).length * trackHeight}px` }"
       @scroll="(e) => scrollY.value = e.target.scrollTop">
      <!-- 虚拟滚动轨道 -->
      <div class="track" v-for="track in visibleTracks" :key="track.id"
           :style="{ transform: `translateY(${visibleStart.value * trackHeight}px)` }">
        <div class="track-header">{{ track.type }}轨道</div>
        <div class="clips-area">
          <!-- 视频片段渲染 -->
          <div
            v-for="clip in track.clips"
            :key="clip.id"
            class="clip"
            :style="{
              left: `${timeToPx(clip.start) - scrollX}px`,
              width: `${timeToPx(clip.duration)}px`,
              backgroundColor: track.type === 'video' ? '#e0f2fe' : track.type === 'audio' ? '#f0f9ff' : '#fef0f2'
            }"
            @mousedown="handleClipDragStart(clip, $event)" @click="() => emits('clip-selected', clip)"
          >
            <div class="clip-content">
              {{ track.type === 'subtitle' ? clip.text : clip.materialId }}
            </div>
            <div class="clip-handle left" @mousedown.stop="handleResizeStart(clip, 'left', $event)"></div>
            <div class="clip-handle right" @mousedown.stop="handleResizeStart(clip, 'right', $event)"></div>
            // 在片段元素添加右键菜单
            <div 
              class="clip-menu"
              @contextmenu.prevent="(e) => {
                e.preventDefault();
                showContextMenu(e, clip);
              }"
            >
            <!-- 添加上下文菜单模板 -->
            <div v-if="contextMenu.visible" class="context-menu" 
                 :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }">
              <button @click="handleDeleteClip(contextMenu.clip.id)">删除片段</button>
              <button @click="() => emits('clip-selected', contextMenu.clip)">设为预览</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>

</template>

<style scoped>
.timeline-container {
  overflow-x: auto;
  border-top: 1px solid #e5e7eb;
}
.timeline-header {
  height: 30px;
  position: relative;
  border-bottom: 1px solid #d1d5db;
}
.time-marker {
  position: absolute;
  font-size: 12px;
  color: #6b7280;
}
.tracks-container {
  position: relative;
  overflow-y: auto;
  height: 300px; /* 固定可视区域高度 */
}
.track {
  margin: 8px 0;
  border: 1px solid #f3f4f6;
  border-radius: 4px;
}
.track-header {
  padding: 4px 8px;
  background: #f8fafc;
  font-size: 14px;
  color: #374151;
}
.clips-area {
  height: 60px;
  position: relative;
}
.clip-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  font-size: 12px;
}
</style>